/*
 * Buffer.c
 *
 *  Created on: 2 mars 2012
 *      Author: Jeff
 */

#include <Arduino.h>
#include "config.h"
#include "Buffer.hpp"
#include "IO.h"

Buffer::Buffer() {
	bufferStatus = SHELL_BUFFERSTATUS_VOID;
	bufferIndex = 0;
}

void Buffer::zero() {
	for (int i=0; i<SHELL_BUFFER_MAX; i++)
		bufferSpace[i] = 0;
	bufferStatus = SHELL_BUFFERSTATUS_VOID;
	bufferIndex = 0;
}

// blocking read, waits for a ';' or '\n' or '\0'
void Buffer::read() {
	byte inByte;
	bufferStatus = SHELL_BUFFERSTATUS_NOAVAIL;

	while (bufferStatus == SHELL_BUFFERSTATUS_NOAVAIL) {
		while (INPUT_AVAILABLE() <= 0);
		inByte = INPUT_READ();
		bufferSpace[bufferIndex] = inByte;
		bufferIndex++;
		if (bufferIndex >= SHELL_BUFFER_MAX) {
			bufferStatus = SHELL_BUFFERSTATUS_MAXREACHED;
			return;
		}
		if (inByte == '\n') {
			bufferStatus = SHELL_BUFFERSTATUS_FILLED;
			return;
		}
		if (inByte == '\0') {
			bufferStatus = SHELL_BUFFERSTATUS_FILLED;
			return;
		}
		if (inByte == ';') {
			bufferStatus = SHELL_BUFFERSTATUS_FILLED;
			return;
		}
	}
//	bufferStatus = SHELL_BUFFERSTATUS_NOAVAIL;
}

void Buffer::display() {
#ifdef SHELL_DEBUG
	OUTPUT_PRINT("BUFFER:\n   max size: ");
	OUTPUT_PRINT(SHELL_BUFFER_MAX);
	OUTPUT_PRINT("\n   bufferIndex: ");
	OUTPUT_PRINT(bufferIndex);
	OUTPUT_PRINT("\n   bufferStatus: ");
	OUTPUT_PRINT(bufferStatus);
	OUTPUT_PRINT("\n   buffer[]: ");
	OUTPUT_WRITE((uint8_t *)bufferSpace,bufferIndex);
	OUTPUT_PRINT('\n');
#endif
}
